<!-- 商品分类列表 -->
<template>
  <s-layout :bgStyle="{ color: '#fff' }" tabbar="/pages/index/category" title="分类">
    <view class="s-category">
      <!-- 选择门店 -->
      <view class="store">
        <view @click="handleSelectStore" class="store-info ss-flex ss-row-start ss-col-center">
          <text class="store-name" style="font-weight: 600">{{
            sheep.$store('selectStore').currentSelect.name
          }}</text>
          <text class="store-distance" v-if="sheep.$store('selectStore').currentSelect.distance"
            >{{ sheep.$store('selectStore').currentSelect.distance }} km</text
          >
          <uni-icons type="arrowright" size="18" color="#666" style="margin-left: 8rpx"></uni-icons>
        </view>
        <!-- 搜索框 -->
        <view style="width: 120px">
          <s-search-block
            :placeholder="'搜索'"
            elBackground="#fff"
            @click="sheep.$router.go('/pages/index/search')"
          ></s-search-block>
        </view>
      </view>
      <view class="three-level-wrap ss-flex ss-col-top" :style="[{ height: pageHeight + 'px' }]">
        <!-- 商品分类（左） -->
        <scroll-view class="side-menu-wrap" scroll-y :style="[{ height: pageHeight + 'px' }]">
          <view
            class="menu-item ss-flex"
            v-for="(item, index) in state.categoryList"
            :key="item.id"
            :class="[{ 'menu-item-active': index === state.activeMenu }]"
            @tap="onMenu(index)"
          >
            <view class="menu-title ss-line-1">
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
        <!-- 商品分类（右） -->
        <view class="right-content" :style="[{ height: pageHeight + 'px' }]">
          <!-- 二级分类 Tabs -->
          <scroll-view
            class="tabs-wrap"
            scroll-x
            scroll-with-animation
            :scroll-left="state.scrollLeft"
            style="height: 45px"
          >
            <view class="tabs-container">
              <view
                v-for="(subCat, subIndex) in currentSubCategories"
                :key="subCat.id"
                class="tab-item"
                :class="{ 'tab-item-active': subIndex === state.activeSubMenu }"
                @tap="onSubMenu(subIndex)"
              >
                {{ subCat.name }}
              </view>
            </view>
          </scroll-view>
          <!-- 商品展示 -->
          <scroll-view
            class="goods-scroll"
            scroll-y
            :style="[{ height: pageHeight - 45 + 'px' }]"
            @scrolltolower="loadMore"
          >
            <view class="goods-list ss-flex ss-flex-wrap ss-p-x-20">
              <view v-for="item in state.goodsList" :key="item.id" class="goods-item">
                <s-goods-column
                  class="goods-md-box"
                  size="md"
                  :data="item"
                  :topRadius="10"
                  :bottomRadius="10"
                  @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
                >
                  <template v-slot:cart>
                    <button class="ss-reset-button cart-btn" />
                  </template>
                </s-goods-column>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
  import sheep from '@/sheep';
  import CategoryApi from '@/sheep/api/product/category';
  import SpuApi from '@/sheep/api/product/spu';
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { computed, reactive, watch, nextTick  } from 'vue';
  import _ from 'lodash-es';
  import { handleTree } from '@/sheep/util';

  const state = reactive({
    categoryList: [], // 商品分类树
    activeMenu: 0, // 选中的一级菜单，在 categoryList 的下标
    activeSubMenu: 0, // 选中的二级菜单索引
    scrollLeft: 0, // 横向滚动位置
    goodsList: [], // 商品列表
    pagination: {}, // 改为对象存储分页信息
    currentCategory: null, // 当前展示的分类信息
    loadStatus: 'more',
  });

  // 当前分类的完整路径（包含一级和二级）
  const currentCategoryPath = computed(() => {
    return {
      mainIndex: state.activeMenu,
      subIndex: state.activeSubMenu,
      categoryId: currentCategoryId.value,
    };
  });
  // 当前分类ID计算
  const currentCategoryId = computed(() => {
    const mainCat = state.categoryList[state.activeMenu];
    if (!mainCat) return null;
    return mainCat.children?.[state.activeSubMenu]?.id || mainCat.id;
  });

  const currentSubCategories = computed(() => {
    if (state.categoryList.length === 0) return [];
    return state.categoryList[state.activeMenu]?.children || [];
  });

  const { safeArea } = sheep.$platform.device;
  const pageHeight = computed(() => safeArea.height - 44 - 50 - 58);

  // 加载商品分类
  async function getList() {
    const { code, data } = await CategoryApi.getCategoryList({
      storeId: sheep.$store('selectStore').currentSelect.id,
    });
    if (code !== 0) {
      return;
    }
    state.categoryList = handleTree(data);
    // 确保有分类数据时自动选中第一个
    if (state.categoryList.length > 0 && !state.categoryList[state.activeMenu]) {
      state.activeMenu = 0;
      state.activeSubMenu = 0;
    }
  }

  // 选中菜单
  const onMenu = (val) => {
    state.activeMenu = val;
    // 新增：重置二级分类选中状态
    state.activeSubMenu = 0;
    state.scrollLeft = 0; // 重置滚动位置
    resetGoodsList();
  };

  // 加载商品列表
  async function getGoodsList() {
    state.loadStatus = 'loading';
    // 加载列表
    const res = await SpuApi.getSpuPage({
      categoryId: currentCategoryId.value,
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
    });
    if (res.code === 0) {
      // 合并数据
      state.goodsList =
        state.pagination.pageNo === 1 ? res.data.list : [...state.goodsList, ...res.data.list];
      const hasMore = state.goodsList.length < res.data.total;
      state.loadStatus = hasMore ? 'more' : 'noMore';
      state.pagination.total = res.data.total;
    } else {
      console.error('商品加载失败', res);
      state.loadStatus = 'noMore';
    }
  }

  // 切换分类时重置数据
  const resetGoodsList = () => {
    state.pagination.pageNo = 1;
    state.goodsList = [];
    state.loadStatus = '';
    getGoodsList();
  };

  //监听切换门店，重新加载第一个分类
  watch(
    () => sheep.$store('selectStore').currentSelect.id,
    async () => {
      state.activeMenu = 0;
      state.activeSubMenu = 0;
      await getList();
      if (state.categoryList.length > 0) {
        resetGoodsList(); // 调用商品加载
      }
    },
  );

  onLoad(async (params) => {
    await getCategoryTree();
    if (state.categoryList.length > 0) {
      const firstTarget = {
        mainIndex: 0,
        subIndex: 0,
      };
      await switchCategory(firstTarget);
    }
    if (params?.id) {
      // 首页点击分类的处理：查找满足条件的分类
      const foundCategory = state.categoryList.find(
        (category) => category.id === Number(params.id),
      );
      // 如果找到则调用 onMenu 自动勾选相应分类，否则调用 onMenu(0) 勾选第一个分类
      onMenu(foundCategory ? state.categoryList.indexOf(foundCategory) : 0);
    }
  });

  //选择门店
  function handleSelectStore() {
    uni.navigateTo({
      url: '/pages/stores/index',
    });
  }

  // 点击二级分类
  const onSubMenu = (subIndex) => {
    state.activeSubMenu = subIndex;
    resetGoodsList(); // 新增
  };

  // 加载更多
  async function loadMore() {
    const categoryId = currentCategoryId.value;
    const pagination = initPagination(categoryId);

    if (!pagination.loaded) {
      pagination.pageNo++;
      const res = await SpuApi.getSpuPage({
        categoryId,
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
      });

      if (res.code === 0) {
        state.goodsList = [...state.goodsList, ...res.data.list];
        pagination.total = res.data.total;
        pagination.loaded = res.data.list.length < res.data.total;
        state.loadStatus = pagination.loaded ? 'more' : 'noMore';
      }
    } else {
      const nextTarget = getNextCategory();
      if (nextTarget) {
        await switchCategory(nextTarget);
      } else {
        state.loadStatus = 'noMore';
      }
    }
  }

  // 初始化分页信息
  function initPagination(categoryId) {
    if (!state.pagination[categoryId]) {
      state.pagination[categoryId] = {
        pageNo: 1,
        pageSize: 6,
        total: 0,
        loaded: false,
      };
    }
    return state.pagination[categoryId];
  }

  // 获取下一个需要加载的分类
  function getNextCategory() {
    const currentMain = state.activeMenu;
    const currentSub = state.activeSubMenu;

    // 先检查当前一级下的后续二级分类
    if (currentSub < (state.categoryList[currentMain]?.children?.length - 1 || 0)) {
      return {
        mainIndex: currentMain,
        subIndex: currentSub + 1,
      };
    }

    // 检查后续一级分类
    if (currentMain < state.categoryList.length - 1) {
      return {
        mainIndex: currentMain + 1,
        subIndex: 0,
      };
    }

    return null;
  }
  // 切换分类
  async function switchCategory(target) {
    state.activeMenu = target.mainIndex;
    state.activeSubMenu = target.subIndex;

    // 更新滚动位置
    await nextTick();
    state.scrollLeft = target.subIndex * 100; // 根据实际样式调整

    // 初始化新分类的分页
    const categoryId = currentCategoryId.value;
    initPagination(categoryId);

    // 加载新分类数据
    await loadCategoryGoods(categoryId);
  }

  // 加载指定分类商品
  async function loadCategoryGoods(categoryId) {
    const pagination = initPagination(categoryId);
    if (pagination.loaded) return;

    const res = await SpuApi.getSpuPage({
      categoryId,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    });

    if (res.code === 0) {
      state.goodsList = res.data.list;
      pagination.total = res.data.total;
      pagination.loaded = res.data.list.length < res.data.total;
      state.loadStatus = pagination.loaded ? 'more' : 'noMore';
    }
  }
  // 获取分类树
  async function getCategoryTree() {
    const { code, data } = await CategoryApi.getCategoryList({
      storeId: sheep.$store('selectStore').currentSelect.id,
    });
    if (code === 0) {
      state.categoryList = handleTree(data);
    }
  }
</script>

<style lang="scss" scoped>
  .s-category {
    :deep() {
      .side-menu-wrap {
        width: 200rpx;
        height: 100%;
        padding-left: 12rpx;
        background-color: #f6f6f6;

        .menu-item {
          width: 100%;
          height: 88rpx;
          position: relative;
          transition: all linear 0.2s;

          .menu-title {
            line-height: 32rpx;
            font-size: 30rpx;
            font-weight: 400;
            color: #333;
            margin-left: 28rpx;
            position: relative;
            z-index: 0;

            &::before {
              content: '';
              width: 64rpx;
              height: 12rpx;
              background: linear-gradient(
                90deg,
                var(--ui-BG-Main-gradient),
                var(--ui-BG-Main-light)
              ) !important;
              position: absolute;
              left: -64rpx;
              bottom: 0;
              z-index: -1;
              transition: all linear 0.2s;
            }
          }

          &.menu-item-active {
            background-color: #fff;
            border-radius: 20rpx 0 0 20rpx;

            &::before {
              content: '';
              position: absolute;
              right: 0;
              bottom: -20rpx;
              width: 20rpx;
              height: 20rpx;
              background: radial-gradient(circle at 0 100%, transparent 20rpx, #fff 0);
            }

            &::after {
              content: '';
              position: absolute;
              top: -20rpx;
              right: 0;
              width: 20rpx;
              height: 20rpx;
              background: radial-gradient(circle at 0% 0%, transparent 20rpx, #fff 0);
            }

            .menu-title {
              font-weight: 600;

              &::before {
                left: 0;
              }
            }
          }
        }
      }

      .right-content {
        width: calc(100vw - 200rpx);
        display: flex;
        flex-direction: column;

        .tabs-wrap {
          display: flex;
          white-space: nowrap;
          height: 80rpx;
          line-height: 80rpx;
          background-color: #fff;
          border-bottom: 1px solid #eee;

          .tab-item {
            padding: 0 20rpx;
            font-size: 30rpx;
            color: #333;

            &.tab-item-active {
              color: var(--ui-BG-Main);
              font-weight: 600;
            }
          }
        }
      }
    }
  }

  .store {
    display: flex;
    padding: 0 6px 0 14px;
    box-sizing: border-box;
    margin: 10px 0;
    &-info {
      width: 68%;
      flex-wrap: nowrap;
    }

    &-name {
      font-size: 18px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 6px;
    }

    .store-distance {
      font-size: 14px;
      color: #007aff;
      margin-right: 6px;
    }
  }

  .tabs-wrap {
    width: 100%;
    height: 80rpx;
    background: #fff;

    .tabs-container {
      display: inline-flex; // 关键：使用行内flex实现横向排列
      height: 100%;
      white-space: nowrap;
      padding: 0 20rpx;
    }

    .tab-item {
      flex-shrink: 0; // 关键：防止元素被压缩
      padding: 0 30rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      color: #666;
      position: relative;
      transition: all 0.3s;

      &-active {
        color: var(--ui-BG-Main);
        font-weight: 600;

        &::after {
          content: '';
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 60%;
          height: 4rpx;
          background: var(--ui-BG-Main);
        }
      }
    }
  }

  .goods-scroll {
    background-color: #f6f6f6;
  }

  .goods-list {
    box-sizing: border-box;
    padding: 10px;

    .goods-item {
      width: calc(50% - 10px);
      margin: 5px;
      background: #fff;
      border-radius: 16rpx;
      overflow: hidden;
      box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
      transition: transform 0.2s;

      &:active {
        transform: scale(0.98);
      }
    }

    .goods-image {
      width: 100%;
      height: 340rpx;
      display: block;
      background-color: #f8f8f8;
    }

    .goods-info {
      padding: 20rpx;

      .goods-title {
        font-size: 28rpx;
        line-height: 1.4;
        color: #333;
        height: 80rpx;
        font-weight: 500;
      }
    }

    .price-box {
      margin-top: 20rpx;

      .price-current {
        color: var(--ui-BG-Main);
        font-size: 32rpx;
        font-weight: 600;
        margin-right: 12rpx;
      }

      .price-original {
        color: #999;
        font-size: 24rpx;
        text-decoration: line-through;
      }

      .cart-btn {
        padding: 8rpx;
        background: rgba(var(--ui-BG-Main-rgb), 0.1);
        border-radius: 50%;
        line-height: 1;
      }
    }
  }
</style>
